<template>
<div class="left-box" v-loading.fullscreen.lock="loadings">
    <div class="search-wrap search-inpt">
        <el-input clearable placeholder="搜索" v-model="filterText">
            <i slot="prefix" class="iconfont icon-sousuo"></i>
        </el-input>
    </div>
    <div class="scroll-bar">
        <el-tree default-expand-all @node-expand="nodeExpand" @node-collapse="nodeCollapse" v-loading="loading" element-loading-background="#f5f5f5" :data="treeData" :props="props" :filter-node-method="filterNode" ref="tree">
            <span class="node-span-wrap" slot-scope="{data}" @contextmenu="handleContextMenu(data, $event)">
                <el-tooltip :open-delay="1000" :enterable="false" effect="dark" :content="data.tableName" placement="bottom">
                    <span class="tree-node-span" :draggable="getChilren(data)" @dragover.prevent @dragstart="dragstart($event, data)" :class="{'is-component': getChilren(data)}">
                        <i :style="{color: colors[data.iconType]}" class="tree-node-icon" :class="`iconfont ${data.iconType}`"></i>
                        <span>{{data.tableName}}</span>
                    </span>
                </el-tooltip>
            </span>
        </el-tree>
    </div>
    <easy-cm tag="dataList" :itemHeight="32" :itemSize="12" :list="cmList" @ecmcb="handleClickMenu" :underline="false" :arrow="true"></easy-cm>
    <confirm-dialog @save="reNameSave" :confirmObj="confirmObj"></confirm-dialog>
    <data-detail v-if="dialogData.show" :dialogData="dialogData"></data-detail>
</div>
</template>

<script>
import {
    mapGetters
} from 'vuex'
import {
    colors
} from '@/js/tool'
import ConfirmDialog from '@/components/ConfirmDialog'
import DataDetail from '../../data/DataDetail'
export default {
    name: 'DataList',
    data () {
        return {
            colors,
            contexMenuItem: null,
            loadings: false,
            dialogData: {
                title: '',
                show: false,
                data: {}
            },
            confirmObj: {
                show: false,
                title: '重命名',
                size: 64,
                value: '',
                placeholder: '数据表名必须包含字母数字以及下划线，并以字母开头'
            },
            cmList: [],
            props: {
                label: 'tableName'
            },
            loading: false,
            filterText: '',
            treeData: []
        }
    },
    components: { DataDetail, ConfirmDialog },
    computed: {
        ...mapGetters({
            projectId: 'common/getProjectId',
            updateDataTable: 'common/getUpdateDataTable'
        })
    },
    watch: {
        filterText (val) {
            this.$refs.tree.filter(val)
        },
        updateDataTable () {
            this.init()
        }
    },
    created () {
        this.init()
    },
    methods: {
        getChilren (data) {
            return !data.children || data.children.length === 0
        },
        nodeCollapse (item) {
            if (item.isFolder) {
                item.iconType = 'icon-catalog-close'
            }
        },
        nodeExpand (item) {
            if (item.isFolder) {
                item.iconType = 'icon-catalog-open'
            }
        },
        handleContextMenu (data, e) {
            this.contexMenuItem = data
            this.cmList = data.flag ? [
                { text: '查看数据表', icon: 'iconfont icon-chakanshujubiao' }
            ] : [
                { text: '查看数据表', icon: 'iconfont icon-chakanshujubiao' },
                { text: '删除', icon: 'iconfont icon-shanchu' }
            ]
            this.$easycm(e, this.$root, 'dataList')
        },
        init () {
            this.loading = true
            const parmas = {
                keyword: '',
                projectId: this.projectId
            }
            this.$post('/experiment/catalog/queryDataSourceCatalog', parmas).then(res => {
                if (res) {
                    const { publicDataTables, projectDataTables } = res
                    this.treeData = []
                    if (publicDataTables) {
                        publicDataTables.forEach(v => { v.flag = true })
                        this.getData(publicDataTables, '公共表', 'icon-catalog-open')
                    }
                    if (projectDataTables) {
                        this.getData(projectDataTables, '项目表', 'icon-catalog-open')
                    }
                }
            }).finally(() => {
                this.loading = false
            })
        },
        getData (children, tableName, iconType) {
            children.forEach(v => {
                v.iconType = 'icon-read-table'
            })
            this.treeData.push({
                tableName,
                iconType,
                isFolder: true,
                children
            })
        },
        dragstart (e, item) {
            e.dataTransfer.setData('item', JSON.stringify(item))
        },
        filterNode (value, data) {
            if (!value) return true
            return data.tableName.indexOf(value) !== -1
        },
        handleClickMenu ([n]) {
            switch (n) {
                case 0:
                    this.checkDataTable()
                    break
                case 1:
                    this.remove()
                    break
            }
        },
        reName () {
            const {
                tableName
            } = this.contexMenuItem
            this.confirmObj = {
                show: true,
                title: '重命名',
                placeholder: '数据表名必须包含字母数字以及下划线，并以字母开头',
                size: 64,
                value: tableName
            }
        },
        checkDataTable () {
            let {
                tableId,
                tableName
            } = this.contexMenuItem
            const params = {
                tableId,
                projectId: this.projectId
            }
            this.loadings = true
            this.$post('/dataSource/viewDataTable', params).then(res => {
                if (res) {
                    res.summary.table = res.table
                    this.dialogData = {
                        title: tableName,
                        show: true,
                        data: res.summary
                    }
                }
            }).finally(() => {
                this.loadings = false
            })
        },
        remove () {
            this.$confirm(`确定要删除数据表<span>[${this.contexMenuItem.tableName}]</span>吗？`, '提示', {
                confirmButtonText: '确 定',
                cancelButtonText: '取 消',
                dangerouslyUseHTMLString: true,
                type: 'warning'
            }).then(() => {
                const params = {
                    projectId: this.projectId,
                    tableIds: [this.contexMenuItem.tableId]
                }
                this.$post('/dataSource/deleteDataTables', params).then(res => {
                    if (res) {
                        this.$message.success('删除成功')
                        this.init()
                    }
                })
            }).catch(() => {})
        },
        reNameSave (tableName) {
            let {
                tableId
            } = this.contexMenuItem
            this.$post('/dataSource/renameDataTable', {
                projectId: this.projectId,
                tableId,
                tableName
            }).then(res => {
                if (res) {
                    this.confirmObj.show = false
                    this.$message.success('保存成功')
                    this.init()
                }
            })
        }
    }
}
</script>
